<script setup>
import { ref, onMounted, watch, nextTick, computed } from 'vue'
import { useRouter } from 'vue-router'
import MarkdownIt from 'markdown-it'
import { getChatHistory } from '../services/api'

const props = defineProps({
  title: {
    type: String,
    required: true
  },
  chatId: {
    type: String,
    default: ''
  },
  userAvatar: {
    type: String,
    default: '👤'
  },
  aiAvatar: {
    type: String,
    default: '🤖'
  },
  isGenerating: {
    type: Boolean,
    default: false
  },
  onStop: {
    type: Function,
    default: null
  }
})

const emit = defineEmits(['send-message', 'update-chat-id'])

const router = useRouter()
const message = ref('')
// 最近一次发送时间，用于节流
const lastSentTime = ref(0)
// 是否允许发送（输入框有内容）
const canSend = computed(() => message.value.trim().length > 0)
const chatMessages = ref([])
const chatContainer = ref(null)
const isLoadingHistory = ref(false)

// 创建markdown解析器实例
const md = new MarkdownIt()

// 获取历史聊天记录
const fetchChatHistory = async () => {
  if (!props.chatId) return
  
  isLoadingHistory.value = true
  try {
    const history = await getChatHistory(props.chatId)
    if (history && history.length > 0) {
      // 清空当前消息
      chatMessages.value = []
      
      // 处理历史消息
      history.forEach(msg => {
        const text = msg.text || msg.textContent || ''
        // 判断消息来源
        const msgType = msg.messageType || (msg.metadata && msg.metadata.messageType)
        const msgTypeLower = (msgType || '').toString().toLowerCase()
        chatMessages.value.push({
          id: Date.now() + Math.random(),
          text,
          isUser: msgTypeLower === 'user',
          timestamp: new Date().toLocaleTimeString(),
          completed: true
        })
      })
    }
  } catch (error) {
    console.error('Failed to fetch chat history:', error)
  } finally {
    isLoadingHistory.value = false
  }
}

const sendMessage = () => {
  const now = Date.now()
  // 节流：300ms 内不允许再次发送，防止回车后立即点击按钮重复
  if (now - lastSentTime.value < 300) return
  lastSentTime.value = now

  if (!message.value.trim()) return
  
  // 添加用户消息到聊天记录
  chatMessages.value.push({
    id: Date.now(),
    text: message.value,
    isUser: true,
    timestamp: new Date().toLocaleTimeString()
  })
  
  // 发送消息到父组件处理
  emit('send-message', message.value)
  
  // 清空输入框
  message.value = ''
}

// 添加AI回复消息
const addAiMessage = (text) => {
  // 检查是否已有正在进行的AI消息
  const lastMessage = chatMessages.value[chatMessages.value.length - 1]
  
  if (lastMessage && !lastMessage.isUser && !lastMessage.completed) {
    // 如果最后一条是未完成的AI消息，则追加内容
    lastMessage.text += text
  } else {
    // 否则创建新的AI消息
    chatMessages.value.push({
      id: Date.now(),
      text: text,
      isUser: false,
      timestamp: new Date().toLocaleTimeString(),
      completed: false
    })
  }
}

// 标记AI消息为已完成
const completeAiMessage = () => {
  const lastMessage = chatMessages.value[chatMessages.value.length - 1]
  if (lastMessage && !lastMessage.isUser) {
    lastMessage.completed = true
  }
}

// 暴露方法和数据给父组件
defineExpose({
  addAiMessage,
  completeAiMessage,
  chatMessages
})

// 监听聊天记录变化，自动滚动到底部
watch(chatMessages, () => {
  nextTick(() => {
    if (chatContainer.value) {
      chatContainer.value.scrollTop = chatContainer.value.scrollHeight
    }
  })
}, { deep: true })

// === 新增：在组件挂载后拉取历史记录 ===
onMounted(() => {
  nextTick(adjustTextareaHeight)
  fetchChatHistory()
})

// === 新增：监听 chatId 变化自动拉取历史记录 ===
watch(() => props.chatId, () => {
  fetchChatHistory()
})

const goBack = () => {
  router.push('/')
}

// 处理键盘事件
const handleKeyDown = (e) => {
  // 如果按下Shift+Enter，则插入换行符而不发送消息
  if (e.key === 'Enter' && e.shiftKey) {
    // 不阻止默认行为，允许插入换行符
    adjustTextareaHeight()
  } 
  // 如果只按下Enter键（没有按Shift），则发送消息
  else if (e.key === 'Enter' && !e.shiftKey) {
    e.preventDefault() // 阻止默认的换行行为
    sendMessage()
  }
}

// 自动调整文本区域高度
const messageInput = ref(null)
const adjustTextareaHeight = () => {
  if (!messageInput.value) return
  
  // 重置高度以获取正确的scrollHeight
  messageInput.value.style.height = 'auto'
  
  // 设置新高度（最小高度为原始高度）
  const newHeight = Math.max(messageInput.value.scrollHeight, 38) // 38px是单行高度
  messageInput.value.style.height = `${newHeight}px`
}

// 监听消息内容变化，自动调整高度
watch(message, () => {
  nextTick(adjustTextareaHeight)
})

const changeRoomId = () => {
  const newId = prompt('请输入新的房间 ID', props.chatId)
  if (newId && newId.trim() && newId.trim() !== props.chatId) {
    emit('update-chat-id', newId.trim())
  }
}
</script>

<template>
  <div class="chat-container">
    <div class="chat-header">
      <button class="back-button" @click="goBack">←</button>
      <h1>{{ title }}</h1>
      <span class="room-id" @click="changeRoomId">{{ chatId }}</span>
      <!-- 新增历史记录按钮 -->
      <button class="history-button" @click="fetchChatHistory" :disabled="isLoadingHistory">
        {{ isLoadingHistory ? '加载中...' : '历史记录' }}
      </button>
    </div>
    
    <div class="chat-messages" ref="chatContainer">
      <div v-for="msg in chatMessages" :key="msg.id" 
           :class="['message', msg.isUser ? 'user-message' : 'ai-message']">
        <div class="avatar">
          <span v-if="msg.isUser">{{ userAvatar }}</span>
          <span v-else>{{ aiAvatar }}</span>
        </div>
        <div class="message-content">
          <div class="message-text" v-if="msg.isUser">{{ msg.text }}</div>
          <div class="message-text" v-else v-html="md.render(msg.text)"></div>
          <div class="message-time">{{ msg.timestamp }}</div>
        </div>
      </div>
    </div>
    
    <div class="chat-input">
      <textarea 
        ref="messageInput"
        v-model="message" 
        placeholder="输入消息..." 
        @keydown="handleKeyDown"
        rows="1"
        class="auto-resize-textarea"
      ></textarea>
      <button v-if="!isGenerating" @click="sendMessage" :disabled="!canSend">发送</button>
      <button v-else @click="onStop && onStop()">停止回答</button>
    </div>
  </div>
</template>

<style scoped>
/* Markdown样式 */
.message-text :deep(pre) {
  background-color: rgba(30, 30, 30, 0.8);
  padding: 0.7rem;
  border-radius: 4px;
  overflow-x: auto;
  margin: 0.3rem 0;
  font-family: 'JetBrains Mono', monospace;
  font-size: 0.9rem;
  line-height: 1.2;
}

.message-text :deep(code) {
  background-color: rgba(30, 30, 30, 0.6);
  padding: 0.2rem 0.4rem;
  border-radius: 3px;
  font-family: 'JetBrains Mono', monospace;
  font-size: 0.9rem;
}

.message-text :deep(a) {
  color: var(--neon-blue);
  text-decoration: none;
  border-bottom: 1px dashed var(--neon-blue);
  transition: all 0.3s ease;
}

.message-text :deep(a:hover) {
  text-shadow: 0 0 8px var(--neon-blue);
  border-bottom: 1px solid var(--neon-blue);
}

.message-text :deep(ul), .message-text :deep(ol) {
  padding-left: 1.5rem;
  margin: 0.3rem 0;
}

.message-text :deep(blockquote) {
  border-left: 3px solid var(--neon-purple);
  padding-left: 1rem;
  margin: 0.3rem 0;
  font-style: italic;
  color: #aaa;
}

.message-text :deep(table) {
  border-collapse: collapse;
  width: 100%;
  margin: 0.3rem 0;
}

.message-text :deep(th), .message-text :deep(td) {
  border: 1px solid rgba(255, 255, 255, 0.1);
  padding: 0.5rem;
  text-align: left;
}

.message-text :deep(th) {
  background-color: rgba(30, 30, 30, 0.6);
}

.message-text :deep(img) {
  max-width: 100%;
  border-radius: 4px;
  margin: 0.3rem 0;
}

.message-text :deep(p),
.message-text :deep(ul),
.message-text :deep(ol),
.message-text :deep(pre),
.message-text :deep(blockquote),
.message-text :deep(table),
.message-text :deep(img) {
  margin-top: 0.2rem !important;
  margin-bottom: 0.2rem !important;
}

/* 亮色模式下的Markdown样式 */
@media (prefers-color-scheme: light) {
  .message-text :deep(pre) {
    background-color: rgba(240, 240, 240, 0.8);
    color: #333;
  }
  
  .message-text :deep(code) {
    background-color: rgba(240, 240, 240, 0.6);
    color: #333;
  }
  
  .message-text :deep(a) {
    color: var(--neon-purple);
    border-bottom: 1px dashed var(--neon-purple);
  }
  
  .message-text :deep(a:hover) {
    text-shadow: 0 0 8px var(--neon-purple);
    border-bottom: 1px solid var(--neon-purple);
  }
  
  .message-text :deep(blockquote) {
    color: #666;
  }
  
  .message-text :deep(th) {
    background-color: rgba(240, 240, 240, 0.6);
  }
}

.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  max-width: 900px;
  margin: 0 auto;
  background-color: var(--darker-bg);
  position: relative;
  overflow: hidden;
  border-radius: 8px;
  box-shadow: 0 0 30px rgba(0, 0, 0, 0.3);
}

.chat-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  border: 1px solid var(--neon-blue);
  border-radius: 8px;
  box-shadow: 0 0 15px var(--neon-blue);
  opacity: 0.3;
  pointer-events: none;
  z-index: 1;
}

@media (max-width: 1024px) {
  .chat-container {
    max-width: 90%;
  }
}

@media (max-width: 768px) {
  .chat-container {
    max-width: 100%;
    height: 100vh;
    border: none;
  }
}

.chat-header {
  display: flex;
  align-items: center;
  padding: 1rem 1.5rem;
  background-color: var(--card-bg);
  border-bottom: 1px solid rgba(0, 243, 255, 0.2);
  position: relative;
  z-index: 2;
  gap: 0.8rem;
}

/* 房间ID样式 */
.room-id {
  cursor: pointer;
  font-size: 0.9rem;
  color: #000;
  border-bottom: 1px dashed #000;
  padding: 0 0.2rem;
  font-weight: 600;
  transition: color 0.3s ease, border-bottom-color 0.3s ease;
}

.room-id:hover {
  color: #333;
  border-bottom-color: #333;
  text-shadow: none;
}

.back-button {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  margin-right: 1rem;
  color: var(--neon-blue);
  padding: 0.2rem 0.5rem;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.back-button:hover {
  color: #fff;
  text-shadow: 0 0 8px var(--neon-blue);
}

.back-button::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(0, 243, 255, 0.2), transparent);
  transition: all 0.5s ease;
}

.back-button:hover::before {
  left: 100%;
}

.chat-header h1 {
  margin: 0;
  font-size: 1.5rem;
  font-weight: 600;
  letter-spacing: 1px;
  background: linear-gradient(90deg, var(--neon-blue), var(--neon-purple));
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  text-shadow: 0 0 5px rgba(0, 243, 255, 0.5);
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 1.5rem;
  display: flex;
  flex-direction: column;
  gap: 1.2rem;
  background-image: 
    radial-gradient(circle at 25% 25%, rgba(42, 47, 66, 0.2) 1%, transparent 5%),
    radial-gradient(circle at 75% 75%, rgba(42, 47, 66, 0.2) 1%, transparent 5%);
  background-size: 40px 40px;
  position: relative;
  z-index: 0;
}

.message {
  display: flex;
  max-width: 80%;
  margin-bottom: 0.5rem;
  animation: fadeIn 0.3s ease-out forwards;
  position: relative;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

.user-message {
  align-self: flex-end;
  flex-direction: row-reverse;
}

.ai-message {
  align-self: flex-start;
}

@media (max-width: 768px) {
  .message {
    max-width: 90%;
  }
  
  .message-content {
    padding: 0.75rem;
  }
  
  .message-text {
    font-size: 0.9rem;
  }
  
  .message-time {
    font-size: 0.7rem;
  }
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: var(--card-bg);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.2rem;
  margin: 0 0.5rem;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.1);
  position: relative;
  z-index: 1;
}

.user-message .avatar {
  border-color: rgba(0, 243, 255, 0.3);
  box-shadow: 0 0 10px rgba(0, 243, 255, 0.1);
}

.ai-message .avatar {
  border-color: rgba(157, 0, 255, 0.3);
  box-shadow: 0 0 10px rgba(157, 0, 255, 0.1);
}

.message-content {
  background-color: var(--card-bg);
  padding: 1rem;
  border-radius: 8px;
  position: relative;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.05);
  backdrop-filter: blur(5px);
  transition: all 0.3s ease;
}

.message-content::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  border-radius: 8px;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.05), transparent);
  pointer-events: none;
}

.user-message .message-content {
  background-color: rgba(0, 243, 255, 0.1);
  border-color: rgba(0, 243, 255, 0.2);
}

.message-text {
  margin-bottom: 0.3rem;
  white-space: pre-wrap;
  line-height: 1.3;
  color: rgba(255, 255, 255, 0.9);
  font-size: 0.95rem;
  position: relative;
  z-index: 1;
}

.message-time {
  font-size: 0.7rem;
  color: rgba(255, 255, 255, 0.5);
  text-align: right;
  margin-top: 0.3rem;
  font-family: 'JetBrains Mono', monospace;
}

.user-message .message-time {
  color: rgba(0, 243, 255, 0.6);
}

.ai-message .message-time {
  color: rgba(157, 0, 255, 0.6);
}

.chat-input {
  display: flex;
  padding: 1rem 1.5rem;
  background-color: var(--card-bg);
  border-top: 1px solid rgba(0, 243, 255, 0.2);
  position: relative;
  z-index: 2;
}

.chat-input::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 1px;
  background: linear-gradient(90deg, transparent, var(--neon-blue), var(--neon-purple), var(--neon-blue), transparent);
  opacity: 0.5;
}

@media (max-width: 768px) {
  .chat-input {
    padding: 0.75rem;
  }
  
  textarea.auto-resize-textarea {
    padding: 0.75rem;
    font-size: 0.9rem;
  }
  
  button {
    padding: 0.5rem 1rem;
    font-size: 0.9rem;
  }
}

.chat-input textarea.auto-resize-textarea {
  flex: 1;
  padding: 0.9rem 1.2rem;
  border: 1px solid rgba(0, 243, 255, 0.2);
  border-radius: 8px;
  background-color: rgba(23, 26, 36, 0.8);
  color: #fff;
  margin-right: 0.8rem;
  resize: none; /* 禁止用户手动调整大小 */
  overflow-y: hidden; /* 隐藏垂直滚动条 */
  line-height: 1.5;
  min-height: 38px; /* 设置最小高度 */
  max-height: 150px; /* 设置最大高度，超过后显示滚动条 */
  transition: all 0.3s ease;
  font-family: inherit;
  font-size: 0.95rem;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1), inset 0 0 5px rgba(0, 0, 0, 0.1);
}

.chat-input textarea.auto-resize-textarea:focus {
  outline: none;
  border-color: var(--neon-blue);
  box-shadow: 0 0 15px rgba(0, 243, 255, 0.2), inset 0 0 5px rgba(0, 0, 0, 0.1);
}

.chat-input textarea.auto-resize-textarea::placeholder {
  color: rgba(255, 255, 255, 0.4);
}

.chat-input button {
  padding: 0.8rem 1.5rem;
  border: 1px solid rgba(0, 243, 255, 0.3);
  border-radius: 8px;
  background-color: rgba(0, 243, 255, 0.1);
  color: var(--neon-blue);
  cursor: pointer;
  font-weight: 600;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  min-width: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.chat-input button::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(0, 243, 255, 0.2), transparent);
  transition: all 0.5s ease;
}

.chat-input button:hover {
  background-color: rgba(0, 243, 255, 0.2);
  color: #fff;
  box-shadow: 0 0 15px rgba(0, 243, 255, 0.3);
}

.chat-input button:hover::before {
  left: 100%;
}

/* 亮色模式适配 */
@media (prefers-color-scheme: light) {
  .message-text {
    color: rgba(0, 0, 0, 0.8);
  }
  
  .message-time {
    color: rgba(0, 0, 0, 0.5);
  }
  
  .user-message .message-time {
    color: rgba(0, 157, 255, 0.7);
  }
  
  .ai-message .message-time {
    color: rgba(157, 0, 255, 0.7);
  }
  
  .chat-input textarea.auto-resize-textarea {
    background-color: rgba(255, 255, 255, 0.9);
    color: #333;
    border-color: rgba(157, 0, 255, 0.2);
  }
  
  .chat-input textarea.auto-resize-textarea::placeholder {
    color: rgba(0, 0, 0, 0.4);
  }
  
  .chat-input textarea.auto-resize-textarea:focus {
    border-color: var(--neon-purple);
    box-shadow: 0 0 15px rgba(157, 0, 255, 0.2), inset 0 0 5px rgba(0, 0, 0, 0.05);
  }
  
  .chat-input button {
    background-color: rgba(157, 0, 255, 0.1);
    color: var(--neon-purple);
    border-color: rgba(157, 0, 255, 0.3);
  }
  
  .chat-input button:hover {
    background-color: rgba(157, 0, 255, 0.2);
    box-shadow: 0 0 15px rgba(157, 0, 255, 0.3);
  }
}

@media (prefers-color-scheme: light) {
  .chat-container {
    background-color: #f5f5f5;
  }
  
  .chat-header {
    background-color: #e5e5e5;
    border-bottom: 1px solid #ddd;
  }
  
  .back-button {
    color: #333;
  }
  
  .avatar {
    background-color: #ddd;
  }
  
  .message-content {
    background-color: #e5e5e5;
    color: #333;
  }
  
  .user-message .message-content {
    background-color: #d1d5db;
  }
  
  .message-time {
    color: #666;
  }
  
  .chat-input {
    background-color: #e5e5e5;
    border-top: 1px solid #ddd;
  }
  
  .chat-input input {
    background-color: #fff;
    color: #333;
  }
  
  .chat-input button {
    background-color: #4a5568;
  }
}

/* 历史记录按钮样式 */
.history-button {
  margin-left: auto;
  background: none;
  border: none;
  color: var(--neon-blue);
  font-size: 0.9rem;
  cursor: pointer;
  padding: 0.3rem 0.6rem;
  position: relative;
  overflow: hidden;
  transition: color 0.3s ease;
}

.history-button::after {
  content: '';
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 2px;
  background: currentColor;
  transform: scaleX(0);
  transform-origin: right;
  transition: transform 0.3s ease;
}

.history-button:hover {
  color: var(--neon-purple);
}

.history-button:hover::after {
  transform-origin: left;
  transform: scaleX(1);
}

.history-button:disabled {
  color: #666;
  cursor: not-allowed;
}
</style>